package org.cgs.web.database;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public final class DatabaseConnector
{ 
	private static final Logger LOGGER = Logger.getLogger(DatabaseConnector.class);
	private static final DatabaseConnector INSTANCE = new DatabaseConnector();
	private transient DataSource dataSource;

	/**
	 * Loads the database information from the data source and prepares for creating connections to the database
	 */
	private DatabaseConnector()
	{
		try
		{
			Context init = new InitialContext();
			Context ctx = (Context) init.lookup("java:comp/env");
			dataSource = (DataSource) ctx.lookup("jdbc/cgsDB");
		} // End try block
		catch (Exception e)
		{
			LOGGER.error("There was a problem finding the database connection content", e);
		} // End catch block
	} // End constructor

	/**
	 * Returns the single instance of this class
	 * 
	 * @return The instance of this class
	 */
	public static DatabaseConnector getInstance()
	{
		return INSTANCE;
	} // End method

	/**
	 * Establishes a connection to the database
	 * 
	 * @return The Connection object
	 */
	public Connection getConnection() throws SQLException
	{
		try
		{
			return dataSource.getConnection();
		} // End try block
		catch (SQLException e)
		{
			LOGGER.error("An exception occurred while attempting to connect to the database", e);
			throw e;
		} // End catch block
	} // End method
} // End class
